import { Action, combineReducers } from '@ngrx/store';
import { List } from 'immutable';
import { actions } from './actions';
import { Todo } from './models/todo';

const todos = (state = List.of(new Todo({ title: '123' })), action: Action) => {
  let todo, title

  switch (action.type) {
    case actions.ui.START_EDITING:
      todo = action.payload
      return state.map((v: Todo) => {
        return v === todo ? v.set('editing', true) : v
      })

    case actions.ui.UPDATE_EDITING: // TODO
      todo = action.payload.todo
      title = action.payload.value
      return state.map((v: Todo) => {
        return v === todo ? v.set('editing', false).set('title', title) : v
      })

    case actions.ui.STOP_EDITING:
      todo = action.payload.todo
      title = action.payload.value
      console.log('stop reducer', title, action.payload)
      return state.map((v: Todo) => {
        return v === todo ? v.set('editing', false).set('title', title) : v
      })

    case actions.ui.CANCEL_EDITING:
      console.log('cancel reducer')
      todo = action.payload
      return state.map((v: Todo) => {
        return v === todo ? v.set('editing', false) : v
      })

    case actions.ui.TOGGLE_COMPLETION:
      todo = action.payload
      return state.map((v: Todo) => {
        return v === todo ? v.set('completed', !todo.completed) : v
      })

    case actions.ui.ADD_TODO:
      title = action.payload
      return title && title.trim() ? state.push(new Todo({ title })) : state
  }
  return state
}

const reducers = combineReducers({
  todos
})

export function reducer(state, action) {
  return reducers(state, action)
}
